package com.megvii.corelib.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.TextView;

import com.megvii.corelib.R;

/**
 * Created by linyue on 16/3/25.
 */
public class RoundedTextView extends TextView
{
    public static final int DEFAULT_CORNER_X = 3;

    public static final int DEFAULT_CORNER_Y = 3;

    protected int backgroundColor = 0;

    protected int cornerX = DEFAULT_CORNER_X;

    protected int cornerY = DEFAULT_CORNER_Y;

    public RoundedTextView(Context context)
    {
        super(context);
        init(context, null);
    }

    public RoundedTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    public RoundedTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs)
    {
        setBackgroundDrawable(null);
        if (attrs != null)
        {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundedTextView);
            setBackgroundColor(array.getColor(R.styleable.RoundedTextView_backgroundColor, 0));
            cornerX = array
                    .getDimensionPixelSize(R.styleable.RoundedTextView_cornerX, DEFAULT_CORNER_X);
            cornerY = array
                    .getDimensionPixelSize(R.styleable.RoundedTextView_cornerX, DEFAULT_CORNER_Y);
        }
    }

    @Override
    public void setBackgroundColor(int color)
    {
        this.backgroundColor = color;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawColor(0);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(backgroundColor);
        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), cornerX, cornerY, paint);
        super.onDraw(canvas);
    }
}
